package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Product;
import com.ruoyi.system.domain.ProductChart;
import com.ruoyi.system.domain.ValidationGroups.Create;
import com.ruoyi.system.domain.ValidationGroups.Select;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.IProductChartService;
import com.ruoyi.system.service.IProductService;
import com.ruoyi.system.service.IProductTelemetryService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestController
@RequestMapping("/system/product.v2")
public class ProductChartController extends BaseController {
    @Autowired
    IProductService productService;

    @Autowired
    IProductTelemetryService productTelemetryService;

    @Autowired
    IProductChartService productChartService;

    @Autowired
    TokenService tokenService;

    @Autowired
    ISysDeptService sysDeptService;

    private AjaxResult checkExistance(ProductChart productChart) {
        Map<String, Object> existance = productChartService.findExistance(productChart);
        if (existance != null) {
            Object name_exists = existance.get("name_exists");
            if (name_exists != null && Integer.parseInt(name_exists.toString()) > 0) { 
                return AjaxResult.error(HttpStatus.ERROR, "图表名称已经存在");
            }
        }
        return null;
    }

    private AjaxResult checkIdentifiers(List<String> identifiers, Integer productId) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("product_id", productId);
        List<Map<String, Object>> productTelemetries = productTelemetryService.enumerate(queryVo);
        List<String> validIdentifiers = new ArrayList<>();
        for (Map<String, Object> productTelemetry : productTelemetries) {
            validIdentifiers.add(productTelemetry.get("user_identifier").toString());
        }
        if (!validIdentifiers.containsAll(identifiers)) {
            return AjaxResult.error("无效的标识符");
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:product:chart:add')")
    @PostMapping(value = "/chart/add", produces = "application/json;charset=UTF-8")
    @Log(title = "产品图表", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody @Validated(Create.class) ProductChart productChart) {
        QueryVo queryVo = new QueryVo();
        Integer productId = productChart.getProductId();
        queryVo.filters.put("id", productId);
        Product product = productService.retrieve(queryVo);
        if (product == null) {
            return AjaxResult.error("无效的产品id");
        }
        AjaxResult ret = checkIdentifiers(productChart.getIdentifiers(), productId);
        if (ret != null) {
            return ret;
        }
        productChart.setIdentifiersString(String.join(",", productChart.getIdentifiers()));
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        String createBy = loginUser.getUsername();
        productChart.setCompanyId(companyId);
        productChart.setCreateBy(createBy);
        productChart.setCreateTime(new Date());
        ret = checkExistance(productChart);
        if (ret != null) {
            return ret;
        }
        Integer id = productChartService.create(productChart);
        if (id != null) {
            return AjaxResult.success(productChart);
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:product:chart:list')")
    @GetMapping(value = "/chart/list", produces = "application/json;charset=UTF-8")
    public Object index(@Validated(Select.class) ProductChart productChart) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("product_id", productChart.getProductId());
        queryVo.filters.put("name", productChart.getName());
        queryVo.filters.put("type", productChart.getType());
        queryVo.filters.put("description", productChart.getDescription());
        queryVo.filters.put("aggregation", productChart.getAggregation());
        startPage();
        List<ProductChart> products = productChartService.index(queryVo);
        return getDataTable(products);
    }

    @PreAuthorize("@ss.hasPermi('system:product:chart:list')")
    @GetMapping(value = "/chart/enum", produces = "application/json;charset=UTF-8")
    public AjaxResult enumerate(@Validated(Select.class) ProductChart productChart) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("product_id", productChart.getProductId());
        queryVo.filters.put("name", productChart.getName());
        return AjaxResult.success(productChartService.enumerate(queryVo));
    }

    @PreAuthorize("@ss.hasPermi('system:product:chart:query')")
    @GetMapping(value = "/chart/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieve(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        ProductChart productChart = productChartService.retrieve(queryVo);
        if (productChart == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        return AjaxResult.success(productChart);
    }

    @PreAuthorize("@ss.hasPermi('system:product:chart:edit')")
    @Log(title = "产品图表", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/chart/edit", produces = "application/json;charset=UTF-8")
    public AjaxResult edit(@RequestBody @Validated(Update.class) ProductChart productChart) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", productChart.getId());
        ProductChart target = productChartService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        queryVo.filters.clear();
        Integer productId = productChart.getProductId();
        queryVo.filters.put("id", productId);
        Product product = productService.retrieve(queryVo);
        if (product == null) {
            return AjaxResult.error("无效的产品id");
        }
        AjaxResult ret = checkIdentifiers(productChart.getIdentifiers(), productId);
        if (ret != null) {
            return ret;
        }
        productChart.setIdentifiersString(String.join(",", productChart.getIdentifiers()));
        productChart.setCompanyId(target.getCompanyId());
        ret = checkExistance(productChart);
        if (ret != null) {
            return ret;
        }
        if (productChartService.update(productChart)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:device:chart:remove')")
    @Log(title = "产品图表", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/chart/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult remove(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        // TODO: [ZY] check related modules
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        if (productChartService.delete(queryVo)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
}
